<template>
  <view class="container-login">
	  <view class="login-header">
	  	<image src='https://youpindou.com/miniProgram/image/showImg?imgUrl=/home/ypd/images/transparent-back.png' mode="widthFix" @click="back()"></image>
	  </view>
    <image src="https://youpindou.com/miniProgram/image/showImg?imgUrl=/home/ypd/images/login-logo.png" mode='widthFix' alt="" />
    <view class='login-box'>
      <block v-if="isCode">
        <view class='user-phone'>
          <input v-model="phone" placeholder='请输入手机号' type="number" />
        </view>
        <view class='user-phoneCode'>
          <input v-model="code" placeholder='请输入验证码' type="number" />
          <view @click="getPhoneCode">
            {{ countDown ? `${countDown}s后重发` : '获取验证码' }}
          </view>
        </view>
        <view class='user-phone'>
          <input v-model="inviteCode" placeholder='推荐码(选填)' />
        </view>
      </block>
      <block v-else>
        <view class='user-phone'>
          <input v-model="phone" placeholder='请输入手机号' type="number" />
        </view>
        <view class='user-phoneCode'>
          <input v-model="password" placeholder='请输入密码' type="password" />
        </view>
        <view class='user-phone'>
          <input v-model="inviteCode" placeholder='推荐码(选填)' />
        </view>
      </block>
	  <!-- #ifndef MP-WEIXIN -->
      <view class="switch">
        <view @click="$goPath(2, `/pagesA/pocketShop/mine/editPass`)">
          <u--text text="忘记密码" size="14" color="#32B499"></u--text>
        </view>
		
		<view @click="switchLogin">
		  <u--text :text="text" size="14" color="#32B499"></u--text>
		</view>
      </view>
	  <!-- #endif -->

      <view @click="handleLogin" class="login-btn">
        登录
      </view>
      <view class='user-text'>
        <u-checkbox shape="circle" @change="handleCheck" :checked="check" activeColor="#32B499"></u-checkbox>
        <view @click="check = !check">
          登录代表您已同意<text @click.stop="$goPath(2, `/pagesA/pocketShop/mine/userAgreement?type=1`)">《隐私政策》</text>、<text
            @click.stop="$goPath(2, `/pagesA/pocketShop/mine/userAgreement?type=2`)">《用户协议》</text>并使用本机号码登录
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import { Base64 } from '@/common/base.js'
import { setToken, setUserInfo } from '@/common/auth'
export default {
  data() {
    return ({
      phone: '',
      code: '',
      inviteCode: '',
      password: '',
      check: false,
      countDown: '', // 设置倒计时初始值
      isCode: true,
      text: '切换密码登录'
    })
  },
  onLoad() {
	  this.inviteCode = uni.getStorageSync('inviteCode') || ''; //获取邀请码
	  uni.removeStorageSync('inviteCode') //清除邀请码缓存
  },
  methods: {
	back() {
		let pageNum = getCurrentPages().length
		//前面没页面的时候返回是跳首页
		pageNum > 1 ? this.$goPath(1) : this.$goPath(4, `/pages/premiumBag/home/index`)
	},
    switchLogin() {
      this.isCode = !this.isCode
      this.code = ''
      this.password = ''
	  this.text = this.isCode ? '切换密码登陆' : '切换验证码登陆'
    },
    //倒计时
    startCountdown() {
      this.countDown = 60;
      const that = this;
      const timer = setInterval(() => {
        if (that.countDown > 0) {
          that.countDown--;  // 每秒减1
        } else {
          clearInterval(timer);  // 倒计时结束，清除定时器
          that.countDown = '';
        }
      }, 1000);
    },

    //发送验证码
    getPhoneCode() {
      let regex = /^((\+)?86|((\+)?86)?)0?1[3456789]\d{9}$/;
      if (this.countDown) return;
      if (!regex.test(this.phone)) return this.$toast('请输入正确的手机号')
      this.$request.getCode({ phone: this.phone, type: 1 }).then(res => {
        if (res.code == 200 && res.isSuccess) {
          this.$toast('验证码发送成功', 2000, 'success')
          this.startCountdown();
        } else {
          this.$toast(res.msg)
        };
      }).catch(err => {
        this.$toast('验证码发送失败')
      });
    },

    //勾选隐私政策、用户协议
    handleCheck(event) {
      this.check = event;
    },
	weixinMiniLogin(phone, code, inviteCode, isCode) {
		let that = this
		uni.login({
		  provider: 'weixin',
		  success: function (loginRes) {
		    if (isCode) {
		      if (code == '') return that.$toast('请输入验证码')
		      const param = { 
					smsCode: code,
					inviteCode,
					phone,
					code: loginRes.code ,
			  };
		      if (inviteCode == '') delete param.inviteCode;
		      that.$request.miniLogin(param).then(res => {
		        if (res.code == 200 && res.isSuccess) {
		          const { data } = res;
				  //小程序获取过来的对象和app反过来了，需要处理
				  // 创建 newData 对象，并将 ddgUserBean 的属性展开复制到 newData 中
				  let newData = {
				      ...data.ddgUserBean,
				      ypdUser: { ...data }
				  };
				  
				  // 删除 newData.ypdUser 中的 ddgUserBean 属性
				  delete newData.ypdUser.ddgUserBean;
		          setToken(newData.token)
		          setUserInfo(newData)
		          uni.hideLoading();
		          that.$toast('登录成功!')
		          setTimeout(() => {
		            uni.reLaunch({ url: '/pages/premiumBag/home/index' });
		          }, 500)
		        } else {
		          uni.hideLoading();
		          that.$toast(res.msg)
		        }
		      })
		    }
		  }
		});
	},
     //登录
    handleLogin() {
      let regex = /^((\+)?86|((\+)?86)?)0?1[3456789]\d{9}$/;
      const { phone, check, code, inviteCode, isCode, password } = this;
      if (!regex.test(phone)) return this.$toast('请输入正确的手机号')
      if (!check) return this.$toast('请阅读并勾选用户协议、隐私政策')
	  // #ifdef MP-WEIXIN
	  // 微信小程序用新接口
	  this.weixinMiniLogin(phone, code, inviteCode, isCode)
	  // #endif
	  //app等用下面的接口
	  // #ifndef MP-WEIXIN
      if (isCode) {
        if (code == '') return this.$toast('请输入验证码')
        const param = { code, inviteCode, phone };
        if (inviteCode == '') delete param.inviteCode;
        this.$request.codeLogin(param).then(res => {
          if (res.code == 200 && res.isSuccess) {
            const { data } = res;
            setToken(data.token)
            setUserInfo(data)
            uni.hideLoading();
            this.$toast('登录成功!')
            setTimeout(() => {
              uni.reLaunch({ url: '/pages/premiumBag/home/index' });
            }, 500)
          } else {
            uni.hideLoading();
            this.$toast(res.msg)
          }
        })
      } else {
        let base = new Base64
        if (password == '') return this.$toast('请输入密码')
        const param = { password: base.encode(password), inviteCode, phone };
        if (inviteCode == '') delete param.inviteCode;
        uni.showLoading({ title: '登录中...' });
        this.$request.passLogin(param).then(res => {
          if (res.code == 200 && res.isSuccess) {
            const { data } = res;
            setToken(data.token)
            setUserInfo(data)
            uni.hideLoading();
            this.$toast('登录成功!')
            setTimeout(() => {
              uni.reLaunch({ url: '/pages/premiumBag/home/index' });
            }, 500)
          } else {
            uni.hideLoading();
            this.$toast(res.msg)
          }
        })
      }
	  // #endif
    },
  }
}
</script>
<style>
.container-login {
  width: 100%;
  height: 100vh;
  background-image: url('https://youpindou.com/miniProgram/image/showImg?imgUrl=/home/ypd/images/login-bgImg.png');
  background-size: cover;
  background-repeat: no-repeat;
  font-family: 'PingFang SC-Medium';
  font-size: 28rpx;
  background-color: #fff;
  display: flex;
  align-items: flex-end;
}

.container-login>image {
  width: 100%;
  height: auto;
  display: block;
  position: relative;
}
.container-login .login-header image{
	width: 70rpx;
	height: 70rpx;
	display: block;
	position: fixed;
	top: 80rpx;
	left: 40rpx;
	z-index: 100000;
}

.container-login .login-box {
  position: absolute;
  width: 100%;
  left: 0;
  bottom: 0;
  padding: 0 2.7rem;
  box-sizing: border-box;
  padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
  box-sizing: border-box;
}

.container-login .login-box>view {
  margin-bottom: 24rpx;
}

.container-login .login-box>view:last-child {
  margin: 0;
}

.container-login .login-box .user-phone {
  border-bottom: 2rpx solid rgba(241, 241, 241, 0.8);
  padding-left: 16rpx;
  padding-bottom: 10rpx;
  box-sizing: border-box;
}

.container-login .login-box .user-phoneCode {
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid rgba(241, 241, 241, 0.8);
  padding: 0 18rpx;
  padding-bottom: 10rpx;
  box-sizing: border-box;
}

.container-login .login-box .user-phoneCode view {
  color: #32B499;
  font-size: 28rpx;
  text-align: center;
}

.container-login .login-box .user-phoneCode input {
  flex: 1;
}

.container-login input {
  width: 100%;
  background: none;
  border: none;
  outline: none;
  display: black;
  line-height: 50rpx;
}

.container-login .login-box .login-btn {
  width: 100%;
  height: 80rpx;
  border-radius: 44rpx;
  margin-bottom: 24rpx;
  background-color: #32B499;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.switch {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}


.container-login .login-box .user-text {
  font-size: 24rpx;
  display: flex;
  align-items: center;
}

.container-login .login-box .user-text text {
  color: #32B499;
}

.uni-input-placeholder {
  font-weight: 400;
  font-family: 'PingFang SC-Medium';
  font-size: 28rpx;
}
</style>